﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.Model;
using SystemFrameWork.Enums;

namespace DAL
{
    public class Sys_UserDAO : EnittyDAO
    {
        /// <summary>
        /// check the use account is existed or not.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pasWord"></param>
        /// <returns></returns>
        public Sys_User CheckUser(string userName, string passWord)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                Sys_User user = mgr.CurrentDataContext.Sys_Users.Where(u => u.UserName == userName && u.Pwd == passWord).FirstOrDefault();
                return user;
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Sys_User LoadUserByName(string userName)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                Sys_User user = mgr.CurrentDataContext.Sys_Users.Where(u => u.UserName == userName).FirstOrDefault();
                return user;
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        public void Insert(Sys_User user)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                mgr.CurrentDataContext.Sys_Users.InsertOnSubmit(user);
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        public void Insert(Sys_RoleUser sru)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                mgr.CurrentDataContext.Sys_RoleUser.InsertOnSubmit(sru);
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// get the moduels which bind up with his function roles from the system 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetFunctionalModule(Sys_User user)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();

                StringBuilder sb = new StringBuilder();
                ///verify the user is whether in the super usergroup
                ///the code below is not correct,result in bugs that can not login the system.
                var superGroup = (from sur in mgr.CurrentDataContext.Sys_RoleUser
                                  join sr in mgr.CurrentDataContext.Sys_Role
                                  on sur.Sys_RoleID equals sr.ID
                                  where sur.Sys_UserID == (Guid)user.ID &&
                                  sr.IsSuperGroup == true
                                  select new { sp = sr.IsSuperGroup }).ToList();

                ///the user group data is illegal
                if (superGroup.Count > 1)
                {
                    throw new DataAccesssException("sorry, the system can not support multi super usergroups!");
                }

                ///in the super group
                if (superGroup.Count == 1)
                {
                    var functions = (from f in mgr.CurrentDataContext.Sys_FunctionModules
                                     join sfr in mgr.CurrentDataContext.Sys_FunctionModuleSys_Role
                                         on f.ID equals sfr.Sys_FunctionModuleID
                                         join sr in mgr.CurrentDataContext.Sys_Role
                                         on sfr.Sys_RoleID equals sr.ID
                                         where f.RecordStatus==(byte)RecordStatus.RecordActive
                                         orderby f.OrderNo ascending
                                     select new { mfunctions = sr.Name }).ToList();

                    foreach (var obj in functions)
                    {
                        sb.Append(obj.mfunctions.ToString());
                        sb.Append(",");
                    }
                }
                else
                {
                    var functions = (from f in mgr.CurrentDataContext.Sys_FunctionModules
                                     join
                                     sfu in mgr.CurrentDataContext.Sys_FunctionModuleSys_Role
                                     on f.ID equals sfu.Sys_FunctionModuleID
                                     join sr in mgr.CurrentDataContext.Sys_Role
                                     on sfu.Sys_RoleID equals sr.ID
                                     join sur in mgr.CurrentDataContext.Sys_RoleUser
                                     on sr.ID equals sur.Sys_RoleID
                                     join su in mgr.CurrentDataContext.Sys_Users
                                     on sur.Sys_UserID equals su.ID
                                     where su.ID == user.ID
                                     && f.RecordStatus == (byte)RecordStatus.RecordActive
                                     orderby f.OrderNo ascending
                                     select new { mfunctions = f.Value }).ToList();

                    foreach (var obj in functions)
                    {
                        sb.Append(obj.mfunctions.ToString());
                        sb.Append(",");
                    }
                }
                if (sb.Length != 0)
                {
                    if (sb.ToString().EndsWith(","))
                    {
                        sb.Remove(sb.ToString().LastIndexOf(','), 1);
                    }
                }
                return sb.ToString();

            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Sys_RoleUser> LoadSys_RoleUser(Guid userId)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                return mgr.CurrentDataContext.Sys_RoleUser.Where(sr => sr.Sys_UserID == userId).ToList();

            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="suv"></param>
        /// <returns></returns>
        public List<SysUserView> LoadSysUserViewByCondition(SysUserView suv)
        {
            try
            {
                int skipNum = (suv.MyPageModel.PageIndex - 1) * suv.MyPageModel.PageSize;
                int takeNum = suv.MyPageModel.PageSize;

                DataContextManager mgr = new DataContextManager();
                List<SysUserView> list = new List<SysUserView>();
                var query = from s in mgr.CurrentDataContext.SysUserViews
                            select s;
                if (!string.IsNullOrEmpty(suv.RealName))
                {
                    query = query.Where(s => s.RealName.Contains(suv.RealName));
                }
                if (!string.IsNullOrEmpty(suv.UserName))
                {
                    query = query.Where(s => s.UserName.Contains(suv.UserName));
                }
                if (!string.IsNullOrEmpty(suv.Sex))
                {
                    query = query.Where(s => s.Sex.Contains(suv.Sex));
                }
                if (!string.IsNullOrEmpty(suv.IDCard))
                {
                    query = query.Where(s => s.IDCard.Contains(suv.IDCard));
                }
                if (!string.IsNullOrEmpty(suv.ParentDNA))
                {
                    query = query.Where(s => s.ParentDNA.Length > suv.ParentDNA.Length && s.ParentDNA.Contains(suv.ParentDNA) || s.DepartmentID == suv.DepartmentID);
                }
                else if (string.IsNullOrEmpty(suv.ParentDNA) && suv.DepartmentID != null)
                {
                    query = query.Where(s => s.DepartmentID == suv.DepartmentID);
                }

                suv.MyPageModel.TotalRecord = query.Count();
                list = SqlHelper.DataSorting<SysUserView>(query, suv.OrderByField, suv.OrderDirection).Skip(skipNum).Take(takeNum).ToList();

                return list;
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public Sys_User LoadSysUserByID(Guid userID)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                return mgr.CurrentDataContext.Sys_Users.Where(u => u.ID == userID).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public SysUserView LoadSysUserViewByID(Guid userID)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                return mgr.CurrentDataContext.SysUserViews.Where(u => u.ID == userID).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        public void Delete(Sys_User user)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                mgr.CurrentDataContext.Sys_Users.DeleteOnSubmit(user);
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleUser"></param>
        public void Delete(Sys_RoleUser roleUser)
        {
            try
            {
                DataContextManager mgr = new DataContextManager();
                mgr.CurrentDataContext.Sys_RoleUser.DeleteOnSubmit(roleUser);
            }
            catch (Exception ex)
            {
                throw new DataAccesssException(ex.Message, ex);
            }
        }
    }
}
